package com.study.utils.systemlog;

import com.alibaba.fastjson2.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Aspect
@Service("systemLogAOPService")
public class SystemLogAOPService {

    @Resource
    private SystemLogService systemLogService;

    @Pointcut("@annotation(com.study.utils.systemlog.SystemLogAOP)")
    public void LogPointCut() {}

    @Around("LogPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        SystemLog systemLog = new SystemLog();

        // 请求路径
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        systemLog.setUrl(request.getRequestURI());

        long start = System.currentTimeMillis();

        // 拦截的方法名称。当前正在执行的方法
        String className = point.getTarget().getClass().getName();
        String methodName = point.getSignature().getName();
        systemLog.setMethodName(className + "." + methodName);

        // 拦截的放参数类型
        MethodSignature msig = (MethodSignature)point.getSignature();

        // 拦截的参数
        String[] parameterNames = msig.getParameterNames();
        Object[] args = point.getArgs();
        Map<String, Object> params = generateParams(parameterNames, args);
        systemLog.setRequestParams(JSON.toJSONString(params));

        try {
            // 获得被拦截的方法
            point.getTarget().getClass().getMethod(methodName, msig.getMethod().getParameterTypes());
        } catch (NoSuchMethodException | SecurityException e1) {
            log.error("获取方法异常:" + e1.getMessage());
        }

        // 执行方法返回对象
        Object object = point.proceed();
        try {
            systemLog.setResponseResult(JSON.toJSONString(object));
            systemLog.setCostTime(System.currentTimeMillis() - start);
            systemLog.setMessage("执行成功！");
        } catch (Throwable e) {
            systemLog.setCostTime(System.currentTimeMillis() - start);
            systemLog.setMessage("执行失败!" + e.getMessage());
            log.error("执行方法[" + methodName + "]异常!" + e.getMessage());
        }
        systemLogService.insertSystemLog(systemLog);
        return object;
    }

    private Map<String,Object> generateParams(String[] paramNames, Object[] values){
        Map<String,Object> rs = new HashMap<>();
        for (int i = 0; i < paramNames.length; i++) {
            rs.put(paramNames[i],values[i]);
        }
        return rs;
    }

}
